//
//  LoginViewController.m
//  PeopleStreet
//
//  Created by 辰领科技 on 16/4/11.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "LoginViewController.h"


@interface LoginViewController ()

@property (weak, nonatomic) IBOutlet UIScrollView *scroView;
@property (strong, nonatomic) IBOutlet UITextField *phoneField;
@property (strong, nonatomic) IBOutlet UITextField *passwordField;
@property (weak, nonatomic) IBOutlet UIButton *loginButton;
@property (weak, nonatomic) IBOutlet UIButton *registerButton;



@end

@implementation LoginViewController

- (void)viewWillDisappear:(BOOL)animated{
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque animated:NO];
}

- (void)viewWillAppear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter]postNotificationName:@"isOne" object:nil];
    if (![[[NSUserDefaults standardUserDefaults]objectForKey:@"one"]isEqualToString:@"1"]) {
        [[NSUserDefaults standardUserDefaults]setObject:@"1" forKey:@"one"];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initViewLayout];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:NO];
}

- (void)initViewLayout{
    
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.scroView];
    _scroView.contentSize = flexibleSize(CGSizeMake(0, 569), NO);
    [_phoneField setValue:kGetColor(163, 163, 163) forKeyPath:@"_placeholderLabel.textColor"];
    [_passwordField setValue:kGetColor(163, 163, 163)  forKeyPath:@"_placeholderLabel.textColor"];
    _loginButton.layer.masksToBounds = YES;
    _loginButton.layer.cornerRadius = 20*VerticalRatio();
    
    _registerButton.layer.masksToBounds = YES;
    _registerButton.layer.cornerRadius = 5*VerticalRatio();
    _registerButton.layer.borderColor = [UIColor colorWithRed:0.773 green:0.839 blue:0.906 alpha:1.000].CGColor;
    _registerButton.layer.borderWidth = 1;
    

    _passwordField.secureTextEntry = YES;
    
}

- (IBAction)bakc:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark == 登录
- (IBAction)loginHandel:(id)sender {
    if ([Common dataIsNULL:_phoneField.text]) {
        [CWHUDTips showTips:_phoneField.placeholder];
        return;
    }
    if ([Common dataIsNULL:_passwordField.text]) {
        [CWHUDTips showTips:_passwordField.placeholder];
        return;
    }
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:[_phoneField.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] forKey:@"username"];
    [dic setObject:[Common md5:_passwordField.text] forKey:@"password"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:F_userLogin withHttpType:@"POST" withTag:F_F_userLogin];
    [self hideKeyBoard];
}

//#pragma mark - md5加密
//- (NSString *) md5:(NSString *) input {
//    const char* str = [input UTF8String];
//    unsigned char result[CC_MD5_DIGEST_LENGTH];
//    CC_MD5(str, strlen(str), result);
//    NSMutableString *ret = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH];
//    
//    for(int i = 0; i<CC_MD5_DIGEST_LENGTH; i++) {
//        [ret appendFormat:@"%02X",result[i]];
//    }
//    return ret;
//}

#pragma mark == 注册
- (IBAction)registHandel:(id)sender {
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"LoginStoryboard" bundle:nil];
    UIViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"Register"];
    [self presentViewController:page animated:YES completion:nil];
}


#pragma mark == 忘记密码
- (IBAction)findPassword:(id)sender {
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"LoginStoryboard" bundle:nil];
    UIViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"GetBackPassword"];
    [self presentViewController:page animated:YES completion:nil];

}




#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    
    if (tag==F_F_userLogin) {
        
        if (  [[database valueForKey:@"type"] integerValue] ==1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            //1. 创建一个plist文件
            NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
            NSString *path=[paths    objectAtIndex:0];
            NSString *filename=[path stringByAppendingPathComponent:@"myUserInfo.plist"];
            
            NSFileManager* fm = [NSFileManager defaultManager];
            [fm createFileAtPath:filename contents:nil attributes:nil];
            NSMutableDictionary * dict = database[@"data"];
            NSDictionary *userinfoDic = @{Key_User_nickname:[self dataIsNull:dict dataStr:@"username"],
                                          Key_User_password:[self dataIsNull:dict dataStr:@"password"],
                                          Key_User_userId:[self dataIsNull:dict dataStr:@"id"],
                                          Key_User_onlineKey:[self dataIsNull:dict dataStr:@"validateCode"],
                                          Key_User_Phone:_phoneField.text,
                                          };
            [userinfoDic writeToFile:filename atomically:YES];
            
            [[NSNotificationCenter defaultCenter]postNotificationName:@"myname" object:nil];
            [[NSUserDefaults standardUserDefaults]setObject:[Common stringFromData:database[@"data"][@"name"]] forKey:@"name"];
            [self dismissViewControllerAnimated:YES completion:nil];
        }else  {
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }
    }
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    //
    [self dismissWaitDialog];
    
    
}

//判断数据是否存在
- (NSString *)dataIsNull:(NSDictionary *)dic dataStr:(NSString *)dataStr{
    if (!dic[dataStr]) {
        return @"";
    }else{
        return dic[dataStr];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
